// 悬浮菜单插件
// 功能：在小屏幕设备上显示悬浮按钮，点击展开侧边导航菜单
// 特点：包含点击痕迹记录、平滑滚动、响应式设计，与顶部导航栏视觉协调
// 增强功能：支持ESC键关闭菜单，蒙板上鼠标显示按钮样式
(function() {
  /**
   * 默认配置参数
   */
  const defaults = {
    maxScreenWidth: 768,                  // 显示菜单的最大屏幕宽度阈值(px)
    buttonColor: '#28a745',               // 悬浮按钮背景色
    buttonSize: 56,                       // 悬浮按钮尺寸(px)
    rightDistance: 30,                    // 按钮到右侧屏幕边缘的距离(px)
    positionFrom: 'top',                  // 按钮定位基准：'top'或'bottom'
    topDistance: 450,                     // 相对顶部定位时的距离(px)
    bottomDistance: 250,                  // 相对底部定位时的距离(px)
    fixedHeaderSelector: '.fixed-top',    // 固定头部选择器
    headerOffset: 15,                     // 头部额外偏移量(px)
    menuHideDelay: 300,                   // 菜单隐藏后延迟滚动的时间(ms)
    menuTitle: '菜单导航',                // 菜单标题文本
    menuItems: [                          // 菜单项配置数组
      { text: '', targetId: '', isEmpty: true},
      { text: '', targetId: '', isEmpty: true },
      { text: '', targetId: '', isEmpty: true},
      { text: '', targetId: '', isEmpty: true },
      { text: '', targetId: '', isEmpty: true},
      { text: '', targetId: '', isEmpty: true },
      { text: '', targetId: '', isEmpty: true}
    ],
    zIndex: 1000,                         // 元素层级优先级
    // 移除快捷键相关配置
    // 点击痕迹样式配置
    clickedStyle: {
      bgColor: 'rgba(0, 123, 255, 0.1)',  // 点击后背景色
      borderLeft: '3px solid #0d6efd'     // 点击后左侧标识边框
    }
  };

  /**
   * 初始化插件
   * @param {Object} options - 用户配置参数
   * @returns {HTMLElement|null} 悬浮按钮元素，不符合显示条件时返回null
   */
  function init(options) {
    const settings = { ...defaults, ...options };

    if (!isScreenWidthValid(settings.maxScreenWidth)) return null;

    const distanceFrom = settings.positionFrom === 'bottom'
        ? settings.bottomDistance
        : settings.topDistance;

    createStyles(settings, distanceFrom);

    const button = createButton(settings);
    const menu = createMenu(settings);
    const overlay = createOverlay(settings);

    document.body.appendChild(button);
    document.body.appendChild(menu);
    document.body.appendChild(overlay);

    // 存储元素引用以便在事件处理中使用
    const menuElements = { button, menu, overlay };
    bindEvents(menuElements, settings);

    return button;
  }

  /**
   * 检测屏幕宽度是否符合菜单显示条件
   */
  function isScreenWidthValid(maxWidth) {
    return window.innerWidth <= maxWidth;
  }

  /**
   * 平滑滚动到目标元素位置
   */
  function scrollToTarget(targetId, settings) {
    const targetElement = document.getElementById(targetId);
    if (!targetElement) {
      console.error(`错误: 未找到ID为"${targetId}"的元素`);
      return false;
    }

    let headerHeight = 0;
    const headerElement = document.querySelector(settings.fixedHeaderSelector);
    if (headerElement) {
      headerHeight = headerElement.offsetHeight;
    }

    const targetPosition =
        targetElement.getBoundingClientRect().top +
        window.pageYOffset -
        headerHeight -
        settings.headerOffset + 8;

    window.scrollTo({
      top: targetPosition,
      behavior: 'smooth'
    });

    return true;
  }

  /**
   * 创建插件所需的样式表
   */
  function createStyles(settings, distanceFrom) {
    if (document.getElementById('floating-menu-styles')) return;

    const positionStyle = settings.positionFrom === 'bottom'
        ? `bottom: ${distanceFrom}px`
        : `top: ${distanceFrom}px`;

    const style = document.createElement('style');
    style.id = 'floating-menu-styles';
    style.textContent = `
      .floating-btn {
        position: fixed;
        right: ${settings.rightDistance}px;
        ${positionStyle};
        width: ${settings.buttonSize}px;
        height: ${settings.buttonSize}px;
        border-radius: 50%;
        background-color: ${settings.buttonColor};
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);
        z-index: ${settings.zIndex + 1};
        transition: transform 0.3s ease;
        border: none;
        font-size: 24px;
        outline: none;
        -webkit-tap-highlight-color: transparent;
        -webkit-touch-callout: none;
        user-select: none;
      }
      
      .floating-btn.active { transform: rotate(135deg); }
      
      .floating-menu {
        position: fixed;
        top: 0;
        left: -100%;
        bottom: 0;
        width: 80%;
        max-width: 300px;
        background-color: white;
        box-shadow: 2px 0 15px rgba(0, 0, 0, 0.1);
        z-index: ${settings.zIndex};
        transition: left 0.3s ease;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
      }
      
      .floating-menu.visible { left: 0; }
      
      .menu-title {
        margin: 0;
        height: 56px;
        line-height: 56px;
        color: white;
        background-color: #212529;
        padding: 0 20px;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid #333;
      }
      
      .menu-items {
        display: flex;
        flex-direction: column;
        padding: 0;
        flex: 1;
        margin-bottom: 0;
      }
      
      .menu-item {
        display: flex;
        align-items: center;
        justify-content: space-between; /* 左右内容分离对齐 */
        color: #333;
        text-decoration: none;
        font-size: 16px;
        padding: 15px 20px;
        transition: all 0.2s;
        border-bottom: 1px solid #f1f1f1;
        outline: none;
        -webkit-tap-highlight-color: transparent;
      }
      
      .menu-item-left {
        display: flex;
        align-items: center;
        /* 关键：文字左对齐，不设置居中 */
        text-align: left;
      }
      
      .menu-item-content {
        display: flex;
        align-items: center;
        width: 100%; /* 确保内容容器占满宽度 */
        justify-content: space-between; /* 主内容和序号两端对齐 */
      }

      .menu-item-number {
        color: #6c757d;
        font-size: 14px;
        font-weight: 500;
        /* 序号靠右显示 */
        text-align: right;
        min-width: 20px;
      }
      
      .menu-item i {
        margin-right: 3px;
        width: 20px;
        text-align: center;
      }
      
      .menu-item:hover {
        background-color: #f8f9fa;
        color: ${settings.buttonColor};
        text-decoration: none;
      }
      
      .menu-item.bg-warning:hover {
        background-color: #ffeeba;
      }
      
      .menu-item.clicked {
        background-color: ${settings.clickedStyle.bgColor};
        border-left: ${settings.clickedStyle.borderLeft};
      }
      
      .menu-item.bg-warning.clicked {
        background-color: rgba(255, 193, 7, 0.2);
      }
      
      .menu-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.2);
        z-index: ${settings.zIndex - 1};
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.3s ease;
      }
      
      .menu-overlay.visible {
        opacity: 1;
        pointer-events: auto;
        cursor: pointer; /* 鼠标移动到蒙板上时显示按钮样式 */
      }

      @media (max-width: 768px) {
        .menu-item {
          font-size: 14px;
          padding: 12px 15px;
        }
      }
    `;

    document.head.appendChild(style);
  }

  /**
   * 创建悬浮按钮元素
   */
  function createButton(settings) {
    const button = document.createElement('button');
    button.className = 'floating-btn';
    button.innerHTML = '<i class="bi bi-list"></i>';
    return button;
  }

  /**
   * 创建菜单容器、标题及菜单项
   */
  function createMenu(settings) {
    const menu = document.createElement('div');
    menu.className = 'floating-menu';

    const title = document.createElement('h3');
    title.className = 'menu-title';
    title.textContent = settings.menuTitle;
    menu.appendChild(title);

    const menuItems = document.createElement('ul');
    menuItems.className = 'menu-items list-unstyled';

    settings.menuItems.forEach((item, index) => {
      const listItem = document.createElement('li');
      const link = document.createElement('a');

      // 序号从1开始计数
      const itemNumber = index + 1;

      link.className = `menu-item w-100 ${!item.isEmpty ? 'bg-warning' : ''}`;
      link.href = 'javascript:void(0);';
      link.dataset.index = index;
      link.dataset.target = item.targetId;

      const iconClass = item.isEmpty
          ? 'bi bi-calendar-check'
          : 'bi bi-calendar-check-fill';

      // 调整结构：左侧图标+文字，右侧序号（明确分离为两个容器）
      const linkContent = `
        <div class="menu-item-left">
          <i class="${iconClass}"></i>
          <span>${item.text}</span>
        </div>
        <span class="menu-item-number">${itemNumber}</span>
      `;

      link.innerHTML = linkContent;
      listItem.appendChild(link);
      menuItems.appendChild(listItem);
    });

    menu.appendChild(menuItems);
    return menu;
  }

  /**
   * 创建遮罩层元素
   */
  function createOverlay(settings) {
    const overlay = document.createElement('div');
    overlay.className = 'menu-overlay';
    return overlay;
  }

  /**
   * 绑定所有事件处理函数
   */
  function bindEvents(elements, settings) {
    const { button, menu, overlay } = elements;

    // 按钮点击事件
    button.addEventListener('click', () => toggleMenu(button, menu, overlay));

    // 遮罩层点击事件
    overlay.addEventListener('click', () => {
      if (menu.classList.contains('visible')) {
        hideMenuAndOverlay(button, menu, overlay);
      }
    });

    // 菜单项点击事件
    menu.querySelectorAll('.menu-item').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const targetId = item.dataset.target;

        menu.querySelectorAll('.menu-item').forEach(link => {
          link.classList.remove('clicked');
        });
        item.classList.add('clicked');

        hideMenuAndOverlay(button, menu, overlay);
        setTimeout(() => {
          scrollToTarget(targetId, settings);
        }, settings.menuHideDelay);
      });
    });

    // 窗口大小变化事件
    window.addEventListener('resize', () => {
      if (!isScreenWidthValid(settings.maxScreenWidth) && menu.classList.contains('visible')) {
        hideMenuAndOverlay(button, menu, overlay);
      }
    });

    // 键盘事件监听 - 只保留ESC键关闭菜单功能
    document.addEventListener('keydown', (e) => {
      // 忽略输入框等元素中的按键
      if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) {
        return;
      }

      // 处理ESC键关闭菜单
      if (e.key === 'Escape' && menu.classList.contains('visible')) {
        hideMenuAndOverlay(button, menu, overlay);
        e.preventDefault();
        e.stopPropagation();
      }
    });
  }

  /**
   * 切换菜单显示/隐藏状态
   */
  function toggleMenu(button, menu, overlay) {
    menu.classList.toggle('visible');
    overlay.classList.toggle('visible');
    button.classList.toggle('active');
  }

  /**
   * 隐藏菜单和遮罩层
   */
  function hideMenuAndOverlay(button, menu, overlay) {
    menu.classList.remove('visible');
    overlay.classList.remove('visible');
    button.classList.remove('active');
  }

  // 暴露插件初始化方法到全局
  window.FloatingMenu = { init };
})();
